﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Aliphant.Datas;
using Aliphant.Interfaces;

namespace Aliphant.IoC
{
    public class Scope : IScope
    {
        private readonly Container _container;
        private readonly Dictionary<Type, object> _scopedInstances = new();

        public Scope(Container container) => _container = container;

        public object Resolve(Type serviceType)
        {
            if (!_container.Registrations.TryGetValue(serviceType, out var registration))
            {
                if (serviceType.IsGenericType && _container.Registrations.TryGetValue(serviceType.GetGenericTypeDefinition(), out registration))
                {
                    registration = registration.MakeGenericType(serviceType.GetGenericArguments());
                }
                else
                {
                    throw new InvalidOperationException($"No registration for type {serviceType}");
                }
            }

            return registration.Lifecycle switch
            {
                LifecycleType.Singleton => _container.RootScope.GetInstance(registration),
                LifecycleType.Scoped => GetInstance(registration),
                LifecycleType.Transient => registration.Factory(this),
                _ => throw new ArgumentOutOfRangeException()
            };
        }

        private object GetInstance(Registration registration)
        {
            lock (_scopedInstances)
            {
                if (!_scopedInstances.TryGetValue(registration.ImplementationType, out var instance))
                {
                    instance = registration.Factory(this);
                    _scopedInstances[registration.ImplementationType] = instance;
                }
                return instance;
            }
        }

        public T Resolve<T>() => (T)Resolve(typeof(T));
        public void Dispose() => _scopedInstances.Clear();
    }
}
